<?php

namespace App\Service;

use App\Models\Common\File;
use App\Models\Common\Media;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class MiniprogramService
{
    public function drawQrcode($qrString)
    {
//        $wechat_app = resolve('wechatApp', [
//            'aliasname'=>'miniprogram',
//        ]);
//        $response = $wechat_app->getClient()->postJson('cgi-bin/wxaapp/createwxaqrcode', [
//            'page' => 'pages/index/index',
//        ]);
//        echo storage_path('app/public/uploads/test.jpg');
//        $response->saveAs(storage_path('app/public/uploads/test.jpg'));
        $file = QrCode::format('png')
            ->size(500)
            ->margin(1)
            ->generate($qrString);

//        Log::debug('qrCodeString', [$qrCodeString]);
//
//        $file = base64_decode($qrCodeString);

        $md5 = md5($file);
        $ext = 'png';

        $path1 = substr($md5, 0, 3);
        $path2 = substr($md5, 3, 3);
        $filename = $md5.'.'.$ext;
        $foldpath = 'uploads/file/'.$path1.'/'.$path2.'/';
        $path = $foldpath . $filename;

        $disk = Storage::disk();

        $isexist = $disk->exists($path);
        if(!$isexist) {
            $result = $disk->put($foldpath.$filename, $file);
            if(!$result) {
                return null;
            }
        }
        $m_file = File::firstOrCreate(
            ['md5'=>$md5],
            [
                'url'=>$path,
                'ext'=>$ext,
                'foldpath'=>$foldpath,
                'filesize'=>strlen($file)
            ]
        );

        $url = $disk->url($path);

        $m_media = Media::firstOrCreate(
            [
                'filename'=>'qrcode.png',
                'url'=>$url,
                'file_id'=>$m_file->id,
                'admin_user_id'=>0,
                'creator_id' => Auth::check() ? Auth::id() : 0,
            ]
        );

        return $m_media;
    }
}
